#include "cookie.h"
#include "cgi.h"

// [password=123456; username=admin]
PARAM getCookie(char *cookies, char *cookie_name){
    PARAM param[50], res;
    int pi = 0, i = 0, j = 0;
    char *p = param[pi].key;

    if(cookies==NULL) return res;

    for (i = 0; i < (int) strlen(cookies); i++) {
        if(cookies[i] == ' '){
            continue;
        } else if (cookies[i] == '=') {
            p[j] = '\0';

            j=0;
            p = param[pi].value;
        } else if (cookies[i] == ';') {
            if(i>0) {
                if(cookies[i-1] == ';')
                    continue;
            }
            p[j] = '\0';
            j=0;
            pi++;

            if(pi< sizeof(param)/sizeof(PARAM)){
                p = param[pi].key;
            } else {
                break;
            }

        } else {
            p[j++] = cookies[i];
        }

    }

    /*for(i=0; i<10; i++){
        printf("c-  %s : %s<br> \n", param[i].key, param[i].value);
    }*/

    for(i=0; i<sizeof(param)/sizeof(PARAM); i++){
        if( strcmp(param[i].key, cookie_name) ==0 ){
            return param[i];
        } else{
        }
    }

    return res;
}

// 0 is valid
int isvalid_cookie(){

    char* http_cookie = getenv("HTTP_COOKIE");
    PARAM cookie_username = getCookie(http_cookie, "username");

    int      isvalid = 0;
    sqlite3  *db  = NULL;
    int      nrow=0,ncolumn=0;
    char     **azResult = NULL;
    char     *zErrMsg = 0;
    char     sql[500];
    int      rc;

    rc = sqlite3_open(PATH_DATABASE,&db);
    if (rc) {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        return 1;

    } else {
        sprintf(sql, "select * from [tb_user] where name = '%s' ", cookie_username.value);

        //printf("Content-type:text/html;charset=utf-8\n\n");
        //printf("%s", sql);

        char *pwd = {0};

        rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
        if (rc != SQLITE_OK) {
            fprintf(stderr,"SQL error:%s\n", zErrMsg);
            sqlite3_close(db);
            return 1;

        } if (*azResult != NULL) {
            // get pwd
            int i, j;
            for(i=0; i<=nrow; i++) {
                if(i==0) continue;
                for(j=0; j<ncolumn; j++) {
                    if( strcmp(azResult[j], "pwd") == 0 ){
                         pwd = azResult[ (i*ncolumn) + j ];
                    }
                }
            }
        }

        if( pwd!=NULL ){
            isvalid = 0;
        } else {
            isvalid = 2;
        }
    }

    sqlite3_close(db);

    if( isvalid == 0 ){
        return 0;

    } else {
        printf("Content-type:text/html;charset=utf-8\n\n");
        //printf("<h2>Pages you visit is login required. [%s]: %d </h2>\n\n",http_cookie, isvalid);
		printf("<h2>Pages you visit is login required.</h2>\n\n");
        printf("<meta http-equiv=\"Refresh\" content=\"30;URL=/\">");
        return 1;

    }
}

int set_cookie(char *username, char *password){
    if( username!=NULL && password!=NULL ){
        // authencated request
        printf("Set-Cookie: username=%s; PATH=/; Max-Age=10800 \n", username);
        printf("Set-Cookie: password=ABCDEF \n");
        printf("Content-type:text/html;charset=utf-8\n\n");
        printf("<meta http-equiv=\"Refresh\" content=\"0;URL=/\">");
        return 0;
    } else {
        printf("Content-type:text/html;charset=utf-8\n\n");
        printf("<meta http-equiv=\"Refresh\" content=\"0;URL=/\">");
        return 1;
    }
}

